package org.fdy.bgadmin.controller.system;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.fdy.bgadmin.entity.SysMenu;
import org.fdy.bgadmin.res.MenuRes;
import org.fdy.bgadmin.service.SysMenuService;
import org.fdy.bgadmin.service.SysRoleService;
import org.fdy.common.core.model.Result;
import org.fdy.common.core.units.LoginUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author fangdy
 * @create 2023-10-22 17:13
 */
@Slf4j
@RestController
@RequestMapping("/api/menus")
@RequiredArgsConstructor
@Api(tags = "系统 菜单接口")
public class MenuController {
    private final SysRoleService sysRoleService;
    private final SysMenuService menuService;

    @GetMapping(value = "/build")
    @ApiOperation("获取前端所需菜单")
    public Result<List<MenuRes>> buildMenus(){
        // 获取用户的所有的菜单
        List<SysMenu> menuDtoList = menuService.findByUser(LoginUtils.getUserId());
        List<MenuRes> resultList = new ArrayList<>();
        List<SysMenu> topList = menuDtoList.stream()
                .filter(x -> Objects.isNull(x.getPid())).collect(Collectors.toList());
        // 目前只用两级
        for (SysMenu sysMenu : topList) {
            MenuRes resMenu = BeanUtil.copyProperties(sysMenu, MenuRes.class);
            buildMenuTree(resMenu,menuDtoList);
            resultList.add(resMenu);
        }
        log.info("buildMenus:{}", resultList);
        return Result.ok(resultList);
    }

    private void buildMenuTree(MenuRes resMenu, List<SysMenu> menuDtoList) {
        List<SysMenu> childrenList = menuDtoList.stream()
                .filter(x -> Objects.equals(x.getPid(), resMenu.getId()))
                .collect(Collectors.toList());
        if (CollUtil.isNotEmpty(childrenList)){
            List<MenuRes> childrens = BeanUtil.copyToList(childrenList, MenuRes.class);
            resMenu.setChildren(childrens);
            for (MenuRes res : childrens) {
                buildMenuTree(res, menuDtoList);
            }
        } else {
            resMenu.setChildren(new ArrayList<>());
        }
    }
}
